<template>
  <div v-loading.fullscreen.lock="fullscreenLoading" class="digital_report_qr">
    <div class="digital_report_qr_left">
      <Common-Slider-Bar
        ref="silderBar"
        :item-view-option="{
          itemTitle: 'PROGRAMNAME2',
          key: 'ID',
          menuTitle: 'PROGRAMNAME2',
        }"
        :search-key="'PROGRAMNAME2'"
        :request="{
          url: url + '/dynamicReportForm/queryBodyByProduce', method: 'post',
          data:searchData}"
        @select="menuChange"
        @fatherSelct="menuChangeFather"
      />
    </div>
    <div class="digital_report_qr_content">
      <div class="top">
        <Skeleton v-if="loading" />
        <template v-if="projectLevelOne">
          <div class="top_left">
            <div class="top_left_qr">
              <vue-qr :text="qrUrlOne" :size="254" />
              <div class="project-info">
                <project-info
                  :project-info="projectInfo"
                  :title="projectTitle"
                  :project-center="projectCenter"
                  :content="content"
                />
              </div>
            </div>
          </div>
          <div class="top_right">
            <project-data :project-data="projectData" />
          </div>
        </template>
        <template v-else>
          <div class="top_left_two">
            <div class="top_left_qr_two">
              <vue-qr :text="qrUrlTwo" :size="254" />
              <div class="project_two">
                <project-info-two
                  :title="projectTitle"
                  :list="projectTwoList"
                  @taskCreat="taskCreatBtn"
                  @taskList="taskListBtn"
                />
              </div>
            </div>
          </div>
        </template>
      </div>
      <div class="echarts">
        <Skeleton v-if="chartLoading" />
        <template v-if="projectLevelOne">
          <projecte-charts :title="projectTitle" :mouth-data="mouthData" />
        </template>
        <template v-else>
          <table-common
            :menu-id="menuId"
            :filter-list="filterList"
          />
        </template>
      </div>
    </div>
    <el-dialog
      title="发布任务"
      :visible.sync="taskFormCreatVisible"
      append-to-body
      width="60%"
      :before-close="handleClose"
    >
      <task-form-creat ref="taskCreatRef" v-model="taskCreat" :user-list="userList" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="taskFormCreatCancel">取 消</el-button>
        <el-button type="primary" @click="taskFormCreadSure">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="任务管理"
      :visible.sync="taskListVisible"
      append-to-body
      width="60%"
      :before-close="handleCloseList"
    >
      <task-table v-model="taskListSearchParams" :task-list="taskList" :total="total" :loading="tableLoading" @taskListSearch="taskListSearch" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="taskListCancel">取 消</el-button>
        <el-button type="primary" @click="taskListCancel">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CommonSliderBar from '@/components/CommonSliderBar';
import { getUserList, releaseTask, getTaskList } from '@/api/user';
import { getToken } from '@/utils/auth.js';
import tableCommon from '@/components/tableCommon/index.vue';
import ProjectInfo from './components/ProjectInfo.vue';
import ProjectInfoTwo from './components/ProjectInfoTwo.vue';
import ProjectData from './components/ProjectData.vue';
import Skeleton from '@/components/Skeleton/index.vue';
import TaskFormCreat from './components/TaskFormCreat.vue';
import TaskTable from './components/TaskTable.vue';
import ProjecteCharts from './components/ProjecteCharts.vue';
import baseUrl from '@/utils/processRequest1';
import { uploadMulti } from '@/api/file';
import vueQr from 'vue-qr';
import debounce from 'lodash/debounce';
import { getGlobal } from '@/utils/global';
import {
  getQueryBodyByProduce
} from '@/api/dynamicInterface';

export default {
  components: {
    CommonSliderBar,
    vueQr,
    ProjectInfo,
    ProjectInfoTwo,
    ProjectData,
    ProjecteCharts,
    tableCommon,
    Skeleton,
    TaskFormCreat,
    TaskTable
  },
  data() {
    return {
      url: '',
      searchData: {},
      projectInfo: {},
      content: '',
      projectTitle: '',
      projectCenter: [],
      projectData: [],
      projectLevelOne: true,
      loading: true,
      chartLoading: true,
      mouthData: [],
      projectTwoList: [],
      menuId: undefined,
      filterList: [],
      qrUrlTwo: '',
      qrUrlOne: '',
      taskFormCreatVisible: false,
      taskCreat: {},
      userList: [],
      fullscreenLoading: false,
      taskListVisible: false,
      taskList: [],
      taskListSearchParams: {},
      total: 0,
      leftMuneRow: {},
      tableLoading: false,
      qrUrl: ''
    };
  },
  watch: {
    'taskListSearchParams.pageIndex': {
      handler(obj) {
        this.getTaskList();
      }
    },
    'taskListSearchParams.pageSize': {
      handler(obj) {
        this.getTaskList();
      }
    }
  },
  created() {
    this.getTaskList = debounce(this.getTaskList, 300);
    this.getSearchData();
    this.init();
    this.getUserList();
    this.getQrUrl();
  },
  methods: {
    init() {
      baseUrl().then(res => {
        this.url = res.url;
        this.$nextTick(() => {
          this.$refs.silderBar.send();
        });
      });
    },
    menuChange(obj) {
      console.log(obj);
      const { value } = obj;
      this.getProjectData(value);
    },
    menuChangeFather(obj) {
      console.log(obj);
      const { value } = obj;
      this.getProjectData(value);
    },
    getSearchData() {
      const { PROGRAMNAME2 } = this.$route.query;
      this.searchData = {
        pageIndex: 0,
        pageSize: 100,
        pageType: 1,
        tableId: 583,
        resultAsTree: true,
        filterList: []
      };
      if (PROGRAMNAME2) {
        this.searchData.filterList.push({
          col: 'PROGRAMNAME2', value: PROGRAMNAME2, symbol: 'eq'
        });
      }
    },
    getProjectData(value) {
      this.leftMuneRow = value;
      // Number(value.PID) ? this.getProjectDataTwoLevel(value) : this.getProjectDataOneLevel(value);
      !value.children ? this.getProjectDataTwoLevel(value) : undefined;
    },
    getQrUrl() {
      getGlobal().then((all) => {
        // console.log(all);
        console.log(all);
        this.qrUrl = all.res.data.qrUrl;
      });
    },
    // 一级项目
    async getProjectDataOneLevel(value) {
      const { PROGRAMCODE, PROGRAMNAME } = value;
      this.projectTitle = PROGRAMNAME;
      this.qrUrlTwo = `${this.qrUrl}?filter=PROGRAMCODE,${PROGRAMCODE}&data=tableId,585&token=1&menuId=1624435828446`;
      this.projectLevelOne = true;
      await this.getQueryBodyByProduce({
        pageIndex: 0,
        pageSize: 10,
        pageType: 1,
        tableId: 584,
        filterList: [
          { col: 'PROGRAMCODE', value: PROGRAMCODE, Symbol: 'eq' }
        ]
      });
      this.getChartsData({
        pageIndex: 0,
        pageSize: 10,
        pageType: 1,
        tableId: 585,
        filterList: [
          { col: 'PROGRAMCODE', value: PROGRAMCODE, Symbol: 'eq' }
        ]
      });
    },
    // 二级项目
    async getProjectDataTwoLevel(value) {
      console.log(this.qrUrl);
      const { PROGRAMNAME2, ID } = value;
      this.taskCreat.PROGRAMCODE2 = ID;
      this.taskCreat.PROGRAMNAME2 = PROGRAMNAME2;
      this.qrUrlTwo = `${this.qrUrl}?filter=PROGRAMCODE2,${value.ID}&data=tableId,588&token=1&menuId=1624435828446`;
      this.projectTitle = PROGRAMNAME2;
      this.projectLevelOne = false;
      !this.menuId && (this.menuId = 1624435828446);
      this.filterList = [
        { col: 'PROGRAMCODE2', value: ID, Symbol: 'eq' }
      ];
      await this.getQueryBodyByProduceTwo({
        pageIndex: 0,
        pageSize: 10,
        pageType: 1,
        tableId: 588,
        filterList: [
          { col: 'PROGRAMCODE2', value: ID, Symbol: 'eq' }
          // { col: 'PROGRAMCODE2', value: PROGRAMCODE2, Symbol: 'eq' }
        ]
      });
      this.chartLoading = false;
    },
    async getQueryBodyByProduce(data) {
      this.loading = true;
      await getQueryBodyByProduce(data).then(res => {
        const { success, data } = res;
        if (success && data) {
          const { DEPARTMENTNAME, WJYJ_XMQSSJ, WJYJ_XMZZSJ, WJYJ_XMLB, WJYJ_XMZJE, PAYMONEY, WBFS, ZJSYL, WJYJ_XMNR } = data[0];
          this.projectCenter = [
            { name: '所属部门', content: DEPARTMENTNAME },
            { name: '开始时间', content: WJYJ_XMQSSJ },
            { name: '结束时间', content: WJYJ_XMZZSJ },
            { name: '项目类别', content: WJYJ_XMLB }
          ];
          this.projectData = [
            { title: '总预算数', svg: 'areaChart', unit: true, num: WJYJ_XMZJE },
            { title: '已拨付数', svg: 'lineChart', unit: true, num: PAYMONEY },
            { title: '未拨付数', svg: 'barChart', unit: true, num: WBFS },
            { title: '资金使用率', svg: 'pointMap', unit: false, num: ZJSYL }
          ];
          this.content = WJYJ_XMNR;
          this.loading = false;
        }
      });
    },
    async getQueryBodyByProduceTwo(data) {
      this.loading = true;
      await getQueryBodyByProduce(data).then(res => {
        const { success, data } = res;
        if (success && data) {
          const { YSMX_YSJE, PAYMONEY, WBF, RATE } = data[0];
          this.projectTwoList = [
            { title: '预算数', num: YSMX_YSJE, change: true },
            { title: '已拨付', num: PAYMONEY, change: true },
            { title: '未拨付', num: WBF, change: true },
            { title: '资金使用率', num: RATE, change: false }
          ];
          this.loading = false;
        }
      });
    },
    async getChartsData(value) {
      this.chartLoading = true;
      await getQueryBodyByProduce(value).then(res => {
        const { success, data } = res;
        if (success && data) {
          this.chartLoading = false;
          this.mouthData = [];
          this.mouthData.length = 12;
          data.forEach(item => {
            const index = Number(item.ZFYF) - 1;
            this.mouthData[index] = item.ZC;
          });
        }
      });
    },

    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
          this.taskFormCreatCancel();
        })
        .catch(_ => {});
    },

    taskCreatBtn() {
      this.taskFormCreatVisible = true;
    },

    getUserList() {
      getUserList({}).then(res => {
        const { success, data } = res;
        if (success && data.length) {
          this.userList = data;
        } else {
          this.userList = [];
        }
      });
    },

    taskFormCreatCancel() {
      const { PROGRAMCODE2, PROGRAMNAME2 } = this.taskCreat;
      this.taskCreat = {
        PROGRAMCODE2,
        PROGRAMNAME2
      };
      this.$refs.taskCreatRef.clearFileList();
      this.taskFormCreatVisible = false;
    },

    async taskFormCreadSure() {
      this.fullscreenLoading = true;
      const { name, people, note, fileList, PROGRAMCODE2, PROGRAMNAME2 } = this.taskCreat;
      const userList = [];
      people && people.length && people.forEach(item => {
        userList.push({
          trueName: item.true_name,
          telephone: item.telephone
        });
      });
      const obj = {
        taskName: name || '',
        remark: note || '',
        userId: getToken('xcUserId'),
        userList,
        PROGRAMCODE2,
        PROGRAMNAME2
      };
      await releaseTask(obj).then(async res => {
        const { message, success, data: { id }} = res;
        if (success && id) {
          if (fileList.length) {
            const { success, message } = await this.fileUpload(fileList, id);
            !success && this.$message.error(message);
          }
          this.taskFormCreatCancel();
          this.$message.success(message);
        } else {
          this.$message.error(message);
        }
      });
      this.fullscreenLoading = false;
    },
    // 附件上传
    fileUpload(arr, id) {
      return new Promise((resolve, reject) => {
        const upfileRequest = new FormData();
        for (let i = 0; i < arr.length; i++) {
          upfileRequest.append('files', arr[i].raw);
        }
        upfileRequest.append('guid', id);
        upfileRequest.append('type', 'FJ01');
        uploadMulti(upfileRequest).then(res => {
          resolve(res);
        });
      });
    },
    taskListBtn() {
      this.taskListVisible = true;
      this.taskListSearchParams = {
        userId: getToken('xcUserId'),
        pageIndex: 1,
        pageSize: 10,
        PROGRAMCODE2: this.leftMuneRow.ID
      };
      // this.getTaskList(this.taskListSearchParams);
    },
    async getTaskList() {
      if (JSON.stringify(this.taskListSearchParams) === '{}') return;
      this.tableLoading = true;
      await getTaskList(this.taskListSearchParams).then(res => {
        const { success, data, message, total } = res;
        if (success && data.length) {
          data.map(item => {
            const nameList = [];
            item.receiver && item.receiver.length && item.receiver.forEach(v => nameList.push(v.trueName));
            item.name = nameList.join(',');
          });
          this.taskList = data;
          this.total = total;
        } else {
          this.taskList = [];
          this.$message.error(message);
          this.total = 0;
        }
      });
      this.tableLoading = false;
    },
    taskListSearch() {
      this.taskListSearchParams.pageIndex = 1;
      this.getTaskList();
    },
    handleCloseList(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
          this.taskListCancel();
        })
        .catch(_ => {});
    },
    taskListCancel() {
      this.taskListVisible = false;
      this.taskListSearchParams = {};
      this.taskList = [];
    }

  }
};
</script>

<style lang='scss' scoped>
  // $vw:1920px;
  // /*像素转换相对单位vw*/
  // @function px2vw($px) {
  //   @return $px / $vw * 100vw;
  // }
  .digital_report_qr{
    height: 100%;
    display: flex;
    .digital_report_qr_left{
      width: 16%;
      // height: calc(100% - 75px);
      background: #ffffff;
    }
    .digital_report_qr_content{
      background-color: #e6e9f0;
      padding: 24px 23px 22px 24px;
      height: 100%;
      flex:1;
      position: relative;
      width: 84%;
      .top{
        position: relative;
        height: 278px;
        display: flex;
        padding-bottom: 24px;
        .top_left{
          width: 45%;
          background: #fff;
          border-radius: 4px;
          .top_left_qr{
            height: 100%;
            display: flex;
            width: 100%;
            .project-info{
              width: calc(100% - 254px);
              padding: 23px 20px 23px 0;
            }
          }
        }
        .top_right{
          width: 55%;
          padding-left: 24px;
        }
        .top_left_two{
          width: 100%;
          background: #fff;
          border-radius: 4px;
          .top_left_qr_two{
            height: 100%;
            display: flex;
            width: 100%;
            .project_two{
              width: calc(100% - 254px);
              padding: 23px 20px 23px 20px;
            }
          }
        }
      }
      .echarts{
        height: calc(100% - 278px);
        background-color: #fff;
        border-radius: 4px;
        position: relative;
        width: 100%;
      }
    }
  }
</style>
